package com.mo.lib.view.keyboards

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import com.king.keyboard.KingKeyboard
import com.mo.lib.R
import com.mo.lib.utils.res.ResUtil
import com.mo.lib.utils.res.getDrawable
import com.xuexiang.xutil.display.DensityUtils

/**
 * @ author：mo
 * @ data：2022/4/8:9:33
 * @ 功能：
 */
/** 省份面板*/
val keyboardProvince = R.xml.keyboard_province

/** 字母和数字面板*/
val keyboardNumber = R.xml.keyboard_num_or_letters

/** 字身份证面板*/
val keyboardId = R.xml.keyboard_id_number

fun KingKeyboard.setConfig(): KingKeyboard {
    setBackgroundResource(R.drawable.aa)
    val coo = getKeyboardViewConfig()
    coo?.keyTextSize = DensityUtils.sp2px(16f)
    coo?.keyTextColor = ResUtil.getColor("#000000")
    coo?.keyBackground = getDrawable(R.drawable.bg_keyboard_car_key)
    coo?.deleteDrawable = getDrawable(R.drawable.keyboard_car_cha)
    coo?.specialKeyBackground = getDrawable(R.drawable.corner_5_solid_ffffff)
    setKeyboardViewConfig(coo!!)
    return this
}

fun KingKeyboard.setCarNumber(editText: EditText) {
    setKeyboardCustom(keyboardProvince)
    register(editText, KingKeyboard.KeyboardType.CUSTOM)
    setKeyboardCustomMore(keyboardNumber)
    editText.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun afterTextChanged(p0: Editable?) {
            p0?.let {
                if (it.isNotEmpty()){
                    sendKey(KingKeyboard.KEYCODE_KING_MORE)
                }else{
                    sendKey(KingKeyboard.KEYCODE_KING_BACK)
                }
            }


        }
    })
}

fun KingKeyboard.setIdNumber(editText: EditText) {
    editText.filters = arrayOf(InputFilter.LengthFilter(18))
    setKeyboardCustom(keyboardId)
    register(editText, KingKeyboard.KeyboardType.CUSTOM)
    setOnKeyExtraListener(object : KingKeyboard.OnKeyListener {
        override fun onKey(editText: View?, primaryCode: Int) {
            when (primaryCode) {
                -999 -> {
                    val editable = (editText as EditText).text
                    val start = editText.selectionStart
                    editable.insert(start, "33")
                }
            }
        }
    })
}